/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dao;

import com.entities.PostType;
import com.entities.Posts;
import com.utilities.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Min Tun
 */
public class PostDAO {

    public PostDAO() {
    }

    public static int insertPost(PostType post) {
        int status = 0;
        Connection con = DBUtil.getConnection();
        PreparedStatement stm = null;
        String query = "insert into Post(id, title, description, posted_date, member_id, priorityID, address)"
                + " values(?, ?, ?, ?, ?, ?, ?)";
        try {
            stm = con.prepareStatement(query);
            stm.setString(1, post.getId());
            stm.setString(2, post.getTitle());
            stm.setString(3, post.getDescription());
            stm.setDate(4, new java.sql.Date(post.getPostedDate().getTime()));
            stm.setString(5, post.getMember());
            stm.setInt(6, post.getPriorityID());
            stm.setString(7, post.getAddress());

            status = stm.executeUpdate();
        } catch (SQLException ex) {
            Logger.getLogger(PostDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return status;
    }

    public Posts loadDataToXML(){
        Posts posts = new Posts();
        Connection con = DBUtil.getConnection();
        String query = "select * from Post";
        ResultSet rs = null;
        try {
            PreparedStatement stm = con.prepareStatement(query);
            rs = stm.executeQuery();
            while(rs.next()){
                PostType p = new PostType();
                p.setId(rs.getString("id"));
                p.setTitle(rs.getString("title"));
                p.setDescription(rs.getString("description"));
                p.setMember(rs.getString("member_id"));
                p.setPriorityID(rs.getInt("priorityID"));
                p.setAddress(rs.getString("address"));
                p.setPostedDate(new java.util.Date(rs.getDate("posted_date").getTime()));
                posts.getPost().add(p);
            }
        } catch (SQLException ex) {
            Logger.getLogger(PostDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return posts;
    }
}
